/*
 * Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <unistd.h>

#include "iot_gpio_ex.h"
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"

#define DELAY_SHORT  500  // 短闪持续时间（毫秒）
#define DELAY_LONG   1500 // 长闪持续时间（毫秒）
#define DELAY_PAUSE  500  // 闪烁间隔时间（毫秒）
#define CYCLE_DELAY 2000  // SOS完整周期间隔

static void LedExampleEntry(void)
{
    // LED3的GPIO初始化
    IoTGpioInit(IOT_IO_NAME_GPIO_6);
    // 设置GPIO9的管脚复用关系为GPIO
    IoSetFunc(IOT_IO_NAME_GPIO_6, IOT_IO_FUNC_GPIO_9_GPIO);
    // GPIO方向设置为输出
    IoTGpioSetDir(IOT_IO_NAME_GPIO_6, IOT_GPIO_DIR_OUT);

    while (1) { // 永久循环
        // 三短闪（S）
        for (int i = 0; i < 3; i++) {
            IoTGpioSetOutputVal(IOT_IO_NAME_GPIO_6, IOT_GPIO_VALUE1);
            TaskMsleep(DELAY_SHORT);
            IoTGpioSetOutputVal(IOT_IO_NAME_GPIO_6, IOT_GPIO_VALUE0);
            TaskMsleep(DELAY_PAUSE);
        }

        // 三长闪（O）
        for (int i = 0; i < 3; i++) {
            IoTGpioSetOutputVal(IOT_IO_NAME_GPIO_6, IOT_GPIO_VALUE1);
            TaskMsleep(DELAY_LONG);
            IoTGpioSetOutputVal(IOT_IO_NAME_GPIO_6, IOT_GPIO_VALUE0);
            TaskMsleep(DELAY_PAUSE);
        }

        // 再三短闪（S）
        for (int i = 0; i < 3; i++) {
            IoTGpioSetOutputVal(IOT_IO_NAME_GPIO_6, IOT_GPIO_VALUE1);
            TaskMsleep(DELAY_SHORT);
            IoTGpioSetOutputVal(IOT_IO_NAME_GPIO_6, IOT_GPIO_VALUE0);
            TaskMsleep(DELAY_PAUSE);
        }

        // 完整SOS周期后延时
        TaskMsleep(CYCLE_DELAY);
    }
}

static void LedControlTask(void)
{
    osThreadAttr_t attr;

    attr.name = "LedCntrolDemo";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024; // 堆栈大小为1024 stack size 1024
    attr.priority = osPriorityNormal;
    if (osThreadNew((osThreadFunc_t)LedExampleEntry, NULL, &attr) == NULL) {
        printf("[LedExample] Failed to create LedTask!\n");
    }
}

APP_FEATURE_INIT(LedControlTask);